package com.cheyunkeji.er.activity.evaluate;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.view.evaluate.CameraSurfaceView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CustomerCameraActivity extends Activity implements View.OnClickListener {

    private static final String TAG = CustomerCameraActivity.class.getSimpleName();
    private static final int TAKE_PHOTO_SIGHT_LEFT_FRONT = 0;
    private static final int TAKE_PHOTO_SIGHT_FRONT = 1;
    private static final int TAKE_PHOTO_SIGHT_RIGHT_BEHIND = 2;
    private static final int TAKE_PHOTO_SIGHT_BEHIND = 3;

    private CameraSurfaceView mView;
    private TextView mTakePicture;
    String filePath;


    private RelativeLayout relately;
    private ImageView iv_show;
    private ImageView ivFrame;
    private ImageView ivOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.er_activity_customer_camera);

        mView = (CameraSurfaceView) findViewById(R.id.CameraView);
        mTakePicture = (TextView) findViewById(R.id.btnTake);


        relately = (RelativeLayout) findViewById(R.id.relately);
        ivFrame = (ImageView) findViewById(R.id.iv_frame);
        iv_show = (ImageView) findViewById(R.id.iv_show);
        ivOverlay = (ImageView) findViewById(R.id.iv_overlay);

        relately.setDrawingCacheEnabled(true);
        relately.buildDrawingCache();
        mTakePicture.setOnClickListener(this);

    }


    String imgPath = null;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {

        if (hasFocus) {
            initBackgroundFrame();
        }
    }

    /**
     * 初始化自定义相机背景
     */
    public void initBackgroundFrame() {

//        if (null != getIntent() && -1 != getIntent().getIntExtra("TAKE_PHOTO_SIGHT", -1)) {
//
//            HashMap<String, String> params = new HashMap<>();
////            params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
////            params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
//            params.put("field", "pscodeimg");
//
//            ApiClient.postForm(HttpConstants.GET_CAR_BASIC_INFO, params, new StringCallback() {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//                    SToast.show("数据获取失败");
//                }
//
//                @Override
//                public void onResponse(String response, int id) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(response).optJSONObject("data");
//                        if (!TextUtils.isEmpty(jsonObject.optString("pscodeimg"))) {
//                            ImageLoadUtil.loadImg(CustomerCameraActivity.this, jsonObject.optString("pscodeimg"), ivOverlay);
//                            Log.e(TAG, "initBackgroundFrame : 挡牌图标路径 ： " + jsonObject.optString("pscodeimg"));
//                        }
//
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            });
//
//
//            switch (getIntent().getIntExtra("TAKE_PHOTO_SIGHT", -1)) {
//
//                case TAKE_PHOTO_SIGHT_LEFT_FRONT:
//                    ivFrame.setImageResource(R.drawable.left_front);
//
//                    RelativeLayout.LayoutParams param1 = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
//                    param1.leftMargin = ivFrame.getWidth() / 5;
//                    param1.bottomMargin = ivFrame.getHeight() / 5;
//                    ivOverlay.setLayoutParams(param1);
//
//                    break;
//
//                case TAKE_PHOTO_SIGHT_FRONT:
//                case TAKE_PHOTO_SIGHT_BEHIND:
//
//                    ivFrame.setImageResource(R.drawable.camera_front);
//
//                    RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
//                    param.leftMargin = (ivFrame.getWidth() - ivOverlay.getWidth()) / 2;
//                    param.bottomMargin = ivFrame.getHeight() / 5;
//                    ivOverlay.setLayoutParams(param);
//
//                    break;
//
//
//                case TAKE_PHOTO_SIGHT_RIGHT_BEHIND:
//
//                    ivFrame.setImageResource(R.drawable.right_behind);
//
//                    RelativeLayout.LayoutParams param2 = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
//                    param2.leftMargin = ivFrame.getWidth() / 5;
//                    param2.bottomMargin = ivFrame.getHeight() / 4;
//                    ivOverlay.setLayoutParams(param2);
//
//                    break;
//
//                default:
//                    break;
//            }
//        }

        switch (getIntent().getIntExtra("TAKE_PHOTO_SIGHT", -1)) {

            case TAKE_PHOTO_SIGHT_LEFT_FRONT:
                ivFrame.setImageResource(R.drawable.er_left_front);

                RelativeLayout.LayoutParams param1 = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
                param1.leftMargin = ivFrame.getWidth() / 5;
                param1.bottomMargin = ivFrame.getHeight() / 5;
                ivOverlay.setLayoutParams(param1);

                break;

            case TAKE_PHOTO_SIGHT_FRONT:
            case TAKE_PHOTO_SIGHT_BEHIND:

                ivFrame.setImageResource(R.drawable.camera_front);

                RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
                param.leftMargin = (ivFrame.getWidth() - ivOverlay.getWidth()) / 2;
                param.bottomMargin = ivFrame.getHeight() / 5;
                ivOverlay.setLayoutParams(param);

                break;


            case TAKE_PHOTO_SIGHT_RIGHT_BEHIND:

                ivFrame.setImageResource(R.drawable.er_right_behind);

                RelativeLayout.LayoutParams param2 = (RelativeLayout.LayoutParams) ivOverlay.getLayoutParams();
                param2.leftMargin = ivFrame.getWidth() / 5;
                param2.bottomMargin = ivFrame.getHeight() / 4;
                ivOverlay.setLayoutParams(param2);

                break;

            default:
                break;
        }
    }


    //创建jpeg图片回调数据对象
    private Camera.PictureCallback jpeg1 = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(final byte[] data, Camera Camera) {
            final Bitmap rightBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            iv_show.setImageBitmap(rightBitmap);
            ivFrame.setVisibility(View.INVISIBLE);
            Bitmap groupBitmap = relately.getDrawingCache();
            imgPath = saveImageFile(groupBitmap);
            Log.e(TAG, "run: 拍照图片路径" + imgPath);

            Intent intent = new Intent();
            intent.putExtra("IMG_PATH", imgPath);
            setResult(RESULT_OK, intent);
            finish();

        }
    };


    private String saveImageFile(Bitmap bmp) {
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "JingPai");
        if (!file.exists()) {
            file.mkdirs();
        }
        File f = new File(file, System.currentTimeMillis() + ".jpg");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            filePath = f.getAbsolutePath();
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
                bmp = null;
            }
        }
        return filePath;
    }


    //创建jpeg图片回调数据对象
    private Camera.PictureCallback jpeg = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera Camera) {
            BufferedOutputStream bos = null;
            Bitmap bm = null;
            try {

                Log.e(TAG, "onPictureTaken: " + data.length);

                // 获得图片
                bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                    Log.i(TAG, "Environment.getExternalStorageDirectory()="+Environment.getExternalStorageDirectory());
                    String filePath = "/sdcard/dyk" + System.currentTimeMillis() + ".jpg";//照片保存路径
//                    String filePath = "/sdcard/Android/data/com.google.android.cameraview.demo/files/Pictures/picture.jpg";
//                    File file = new File(filePath);
                    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "cheyun" + System.currentTimeMillis() + ".jpg");
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    bos = new BufferedOutputStream(new FileOutputStream(file));
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);//将图片压缩到流中

                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(file);
                    intent.setData(uri);
                    sendBroadcast(intent);

                } else {
                    Toast.makeText(CustomerCameraActivity.this, "没有检测到内存卡", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bos.flush();//输出
                    bos.close();//关闭
                    bm.recycle();// 回收bitmap空间
//                    mCamera.stopPreview();// 关闭预览
//                    mCamera.startPreview();// 开启预览
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btnTake:
                //拍照
                mView.takePicture(jpeg1);

//               防止双击拍照按钮
                mTakePicture.setEnabled(false);

                break;
            default:
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
